// e37.groovy
/*
The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

Find the sum of the only eleven primes that are both truncatable from left to right and right to left.

NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
*/
boolean isPrime(s) {
    s.toBigInteger().isProbablePrime(9)
}

String chomp(s) {
    s.length() < 2 ? '' : s[0..-2]
}

def chop(s) {
    s.length() < 2 ? '' : s[1..-1]
}

boolean isTruncPrimeLeft(s) {
    if (s == '') return true
    isPrime(s) && isTruncPrimeLeft(chop(s))
}

boolean isTruncPrimeRight(s) {
    if (s == '') return true
    isPrime(s) && isTruncPrimeRight(chomp(s))
}

boolean isWinner(s) {
    isTruncPrimeLeft(s) && isTruncPrimeRight(s)
}

primes = new File("primes.txt").readLines()
winners = []
primes[4..-1].each { prime -> 
    if (isWinner(prime)) {
        winners << prime.toInteger()
    }
}

println "Count: ${winners.size()} Winners: ${winners.sort()} Sum: ${winners.sum()}"
